package com.aco.fatureapp.auxiliary;

import java.util.HashMap;
import java.util.List;
import java.util.Set;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import br.com.ac.fatureweb.integration.billing.LogLeituraVO.TypeRetencao;

import com.aco.fatureapp.R;

@SuppressLint("UseSparseArrays")
public class FaturaRetidaAdapter extends ArrayAdapter<FaturaRetidaItem> {

	HashMap<Integer, Boolean> mSelection = new HashMap<Integer, Boolean>();

	List<FaturaRetidaItem> lstFaturaRetida;

	Context context;

	int layoutResId;

	public FaturaRetidaAdapter(final Context context,
			final int layoutResourceID, final List<FaturaRetidaItem> listItems) {
		super(context, layoutResourceID, listItems);
		this.context = context;
		this.lstFaturaRetida = listItems;
		this.layoutResId = layoutResourceID;

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.widget.ArrayAdapter#getView(int, android.view.View,
	 * android.view.ViewGroup)
	 */
	@Override
	public View getView(final int position, final View convertView,
			final ViewGroup parent) {
		FaturaRetidaItemHolder holder;

		View view = convertView;

		final LayoutInflater inflater = ((Activity) context)
				.getLayoutInflater();

		holder = new FaturaRetidaItemHolder();

		if (lstFaturaRetida != null && !lstFaturaRetida.isEmpty()) {
			final FaturaRetidaItem item = this.lstFaturaRetida.get(position);

			view = inflater.inflate(layoutResId, parent, false);

			if (mSelection.get(position) != null) {
				view.setBackgroundColor(context.getResources().getColor(
						android.R.color.darker_gray));
			}

			holder.inscricao = (TextView) view.findViewById(R.id.txtInscricao);

			holder.tipoRetencao = (TextView) view
					.findViewById(R.id.txtTipoRetencao);

			holder.codOcorrencia = (TextView) view
					.findViewById(R.id.txtCodOcorrencia);

			view.setTag(holder);

			holder.tipoRetencao.setText(TypeRetencao.valueOf(
					item.getTipoRetencao()).getDescricao());

			holder.inscricao.setText(item.getInscricao().toString());

			holder.codOcorrencia.setText(item.getCodOcorrencia().toString());
		}

		return view;
	}

	private static class FaturaRetidaItemHolder {
		TextView inscricao, tipoRetencao, codOcorrencia;
	}

	public void clearSelection() {
		mSelection = new HashMap<Integer, Boolean>();
		notifyDataSetChanged();
	}

	public void setNewSelection(int position, boolean checked) {
		mSelection.put(position, checked);
		notifyDataSetChanged();
	}

	public Set<Integer> getCurrentCheckedPosition() {
		return mSelection.keySet();
	}

	public void removeSelection(int position) {
		mSelection.remove(position);
		notifyDataSetChanged();
	}

	public boolean isPositionChecked(int position) {
		Boolean result = mSelection.get(position);
		return result == null ? false : result;
	}
}